package com.alisms.utils;


import com.alibaba.fastjson.JSONObject;
import com.alisms.config.AliyunSSMConfig;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AliyunSMSUtils {

    @Resource
    private AliyunSSMConfig aliyunSSMConfig;

    /**
     * 发送短信
     *
     * @param phone 手机号
     * @param code  验证码
     */
    public boolean sendMessage(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile(aliyunSSMConfig.getRegionId(),
                aliyunSSMConfig.getAccessKeyId(), aliyunSSMConfig.getSecret());
        //客服端对象
        IAcsClient client = new DefaultAcsClient(profile);
        //请求对象
        CommonRequest request = new CommonRequest();
        //请求方式
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSSMConfig.getDomain());
        request.setSysVersion(aliyunSSMConfig.getVersion());
        //具体操作
        request.setSysAction(aliyunSSMConfig.getAction());
        request.putQueryParameter("RegionId", aliyunSSMConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", aliyunSSMConfig.getSignName());
        request.putQueryParameter("TemplateCode", aliyunSSMConfig.getTemplateCode());
        // 参数  和模板里的格式一样
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

        try {
            //响应对象
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            // 获取状态码  （固定）
            String status = JSONObject.parseObject(response.getData()).get("Code").toString();
            return "OK".equals(status);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}

